import { BaseResponse } from '@/common/BaseResponse';
import { UserTempMessage } from '@/dto/user-temp-redis.dto';
import { User } from '@/entity/user.entity';
import { HTTP_CUSTOM_CODE } from '@/enum/http-custom-code';
import { HttpException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service';
import { CodeDto } from './dto/code.dto';
import { LoginDto } from './dto/login.dto';
import { PhoneLoginDto } from './dto/phone-login.dto';
import { sendRandomCode } from './utils';
@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  async validateUser(loginDto: LoginDto): Promise<any> {
    return {
      username: '',
    };
  }

  async login(loginDto: LoginDto) {
    //  手机号登陆
    const payload = '';
    return {
      data: {
        token: `Bearer ${this.jwtService.sign(payload)}`,
      },
    };
  }

  async getToken(user: User) {
    const token = await this.jwtService.sign({
      id: user.id,
      phone: user.phone,
    });
    await this.userService.setUserInfoToRedisByToken(user);
    return token;
  }

  async mockLogin() {
    const user = await this.userService.findOneByPhone('18950676900');
    let token = '';
    // 已存在
    if (user) {
      console.log('已存在');
      token = await this.getToken(user);
      return BaseResponse.toSuccesJustData({
        token,
        userInfo: user,
      });
    }
    return BaseResponse.toError(
      HTTP_CUSTOM_CODE.USER_REGISTRY_FAILURE,
      '获取用户失败',
    );
  }

  /**
   * 使用手机号登陆
   */
  async loginByPhone(phoneLoginDto: PhoneLoginDto) {
    const res = await this.userService.getTempUserMessage(phoneLoginDto.token);
    // 校验验证码是否正确
    if (phoneLoginDto.code === res.code) {
      // 判断用户是否存在，不存在则进行注册用户
      const user = await this.userService.findOneByPhone(phoneLoginDto.phone);
      let token = '';
      // 已存在
      if (user) {
        console.log('已存在');
        token = await this.getToken(user);
        return BaseResponse.toSuccesJustData({
          token,
          userInfo: user,
        });
      }

      // 不存在则进行注册
      console.log('不存在则进行注册');
      const registryUser = await this.userService.insertUser(phoneLoginDto);
      if (!registryUser) {
        return BaseResponse.toError(
          HTTP_CUSTOM_CODE.USER_REGISTRY_FAILURE,
          '注册用户失败',
        );
      }
      return BaseResponse.toSuccesJustData({
        token: await this.getToken(registryUser),
        userInfo: registryUser,
      });
    }
    return BaseResponse.toCutomResponseJustMsg(
      HTTP_CUSTOM_CODE.VERIFICATION_CODE_SEND_ERROR,
      '验证码不存在',
    );
  }

  async getCode(codeDto: CodeDto) {
    try {
      const res = await sendRandomCode(codeDto.phone);
      await this.userService.setTempUser(res);
      return res.token;
    } catch (error) {
      console.error(error);

      throw new HttpException(
        '短信发送失败',
        HTTP_CUSTOM_CODE.VERIFICATION_CODE_SEND_FAILURE,
      );
    }
  }

  async checkCode(userTempMessage: UserTempMessage) {
    const res = await this.userService.getTempUserMessage(
      userTempMessage.token,
    );
    if (res.code === userTempMessage.code) {
      return BaseResponse.toSuccesJustMsg('验证码正确');
    }
    return BaseResponse.toCutomResponseJustMsg(
      HTTP_CUSTOM_CODE.VERIFICATION_CODE_SEND_ERROR,
      '验证码错误',
    );
  }
}
